import axios from 'axios'
import Message from '@/components/message'
import useStore from '@/store'
// const {user}  = useStore()  .报错  网端初始化时 pinia中的模块还没有创建完毕

// 备用接口地址: http://pcapi-xiaotuxian-front-devtest.itheima.net/
const instance  = axios.create({
    baseURL:'http://pcapi-xiaotuxian-front.itheima.net/',
    timeout:3000
})

// axios的拦截器
instance.interceptors.request.use((config)=>{
    
    // 统一添加token
    const {user}  = useStore()
    if(user.profile.token){
        config.headers.Authorization = `Bearer ${user.profile.token}`
    }

    return config
},(error)=>{
    return Promise.reject(error)
})

instance.interceptors.response.use((response)=>{
    return response
},(error)=>{
    // 4xx 5xx响应错误
    // console.log(error);
    Message.error(error.response.data.message)  
    return Promise.reject(error)
})


export default instance